package com.bawei.websocketdemo

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings
import android.view.View
import androidx.annotation.NonNull
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        println(isIgnoringBatteryOptimizations().toString())

//        if(!isIgnoringBatteryOptimizations()){
//            requestIgnoreBatteryOptimizations()
//        }
//
//        println(isIgnoringBatteryOptimizations().toString())
//        println(isIgnoringBatteryOptimizations().toString())
//        println(isIgnoringBatteryOptimizations().toString())
//        println(isIgnoringBatteryOptimizations().toString())

//        goHuaweiSetting()

        startService(Intent(this,MyService::class.java))

    }
    private fun goHuaweiSetting() {
        try {
            showActivity("com.huawei.systemmanager",
                "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity")
        } catch (e: java.lang.Exception) {
            showActivity("com.huawei.systemmanager",
                "com.huawei.systemmanager.optimize.bootstart.BootStartActivity")
        }
    }

    /**
     * 跳转到指定应用的首页
     */
    private fun showActivity(@NonNull packageName: String) {
        val intent = packageManager.getLaunchIntentForPackage(packageName)
        startActivity(intent)
    }

    /**
     * 跳转到指定应用的指定页面
     */
    private fun showActivity(@NonNull packageName: String, @NonNull activityDir: String) {
        val intent = Intent()
        intent.component = ComponentName(packageName, activityDir)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)
    }

    fun live(view: View) {
        App.websocket.sendMsg("#live#"+"|"+"yaotianxue"+"|"+"hahaha")

    }
    //判断我们的应用是否在白名单中：
    @RequiresApi(api = Build.VERSION_CODES.M)
    private fun isIgnoringBatteryOptimizations(): Boolean {
        var isIgnoring = false
        val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(packageName)
        }
        return isIgnoring
    }
//如果不在白名单中，可以通过以下代码申请加入白名单：
    @RequiresApi(api = Build.VERSION_CODES.M)
    fun requestIgnoreBatteryOptimizations() {
        try {
            val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
            intent.data = Uri.parse("package:$packageName")
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}